#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 1. 创建socket对象
    socket = new QUdpSocket(this);
    // 2. 设置窗口标题
    this->setWindowTitle("服务端");
    // 3. 连接信号槽
    connect(socket, &QUdpSocket::readyRead, this, &Widget::processRequest);
    // 4. 绑定端口号,接受所有的IP地址
    bool ret = socket->bind(QHostAddress::Any, 9090);
    if(!ret) {
        // 绑定失败
        QMessageBox::critical(this, "服务器启动失败", socket->errorString());
        return;
    }
}

Widget::~Widget()
{
    delete ui;
}

QString Widget::process(const QString &request)
{
    // 回显服务器
    return request;
}

// 服务器处理请求
void Widget::processRequest()
{
    // 1. 读取请求并解析
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram();
    QString request = requestDatagram.data(); // 返回QByteArray,隐式转换为QString
    // 2. 根据请求计算响应
    const QString& response = process(request);
    // 3. 将响应回给客户端 (客户端信息包含在requestDatagram中)
    QNetworkDatagram responseDatagram(response.toUtf8(), requestDatagram.senderAddress(), requestDatagram.senderPort());
    socket->writeDatagram(responseDatagram);
    // 把交互的信息显示到界面上
    QString log = "[" + requestDatagram.senderAddress().toString() + ":" + QString::number(requestDatagram.senderPort())
                  + "] request: " + request + ", response: " + response;
    ui->listWidget->addItem(log);
}
